import * as services from 'services/family';
import { Toast } from 'antd-mobile';
import { routerRedux } from 'dva/router';

export default {
  namespace: 'family',
  // 家庭组对应的接口调用

  state: {
    members: [],
    member: {},
    gender: 0,
  },

  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },

    clear(state) {
      return { ...state, member: {} };
    },
  },

  effects: {
    * fetchMembers({ payload }, { call, put }) {
      const auth = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid")));
      if(auth){
        let patientId = auth.patientId;
        let hospitalId = auth.hospitalId;
        const FamilyMembers = yield call(services.getFamilyList, patientId, hospitalId);
        yield put({ type: 'save', payload: { members: FamilyMembers.data || [] } });
      }
    },

    * fetchMember({ payload: id }, { call, put }) {
      const member = yield call(services.getFamilyMember, id);
      yield put({ type: 'save', payload: { member: member.data || {}, gender: member.data.gender } });
    },

    * fetchPatient({ payload: { doctorid, patientid } }, { call, put }) {
      const member = yield call(services.getPatient, doctorid, patientid);
      yield put({ type: 'save', payload: { member: member || {} } });
    },

    * createMember({ payload: data }, { call, put }) {
      const add = yield call(services.addFamilyMember, data);
      if(add.code == 200){
         yield put(routerRedux.goBack());
         Toast.success('添加成员成功');
      }else{
         Toast.success(add.message);
      }
    },

    * deleteMember({ payload: id }, { call, put }) {
      const del = yield call(services.deleteFamilyMember, id);
      if(del.code == 200){
        Toast.success('删除成员成功');
        yield put(routerRedux.goBack());
      }else{
        Toast.fail(del.message);
      }
      
    },

    * updateMember({ payload: data }, { call, put }) {
      const update = yield call(services.updateFamilyMember, data);
      if(update.code == 200){
        Toast.success('更新成功');
        yield put(routerRedux.goBack());
      }else{
        Toast.fail(update.message);
      }
    },

    * reload(action, { put, select }) {
      yield put({ type: 'fetch', payload });
    },

    * restore(action, { put }) {
      yield put({ type: 'clear' });
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query, ...rest }) => {
        if (/family$/.test(pathname)) {
          dispatch({ type: 'fetchMembers'});
        }

        if (/family\/update$/.test(pathname)) {
          dispatch({ type: 'fetchMember', payload: rest.state.memberId});
        }

        if (/family\/add$/.test(pathname)) {
          dispatch({ type: 'restore' });
        }
      });
    },
  },
};
